<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工薪资管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
    /* 基础样式继承 */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    }

    /* 主容器优化 */
    .module-section {
        padding: 2rem 3rem;
        background: #f5f7fb;
        min-height: 100vh;
    }

    /* 卡片样式增强 */
    .card {
        background: white;
        border-radius: 1.2rem;
        box-shadow: 0 4px 6px rgba(62, 73, 89, 0.06);
        padding: 2rem;
        margin-bottom: 2rem;
        border: 1px solid #e8ebf3;
    }

    /* 标题系统 */
    .module-title {
        font-size: 1.75rem;
        color: #1a1d2c;
        margin-bottom: 2rem;
        display: flex;
        align-items: center;
        gap: 1rem;
        font-weight: 600;
    }

    .module-title i {
        color: #657ef8;
        font-size: 1.4em;
    }

    /* 三栏表单布局 */
    .triple-column-form {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 2rem;
        margin-top: 1.5rem;
    }

    /* 表单元素优化 */
    .form-group label {
        display: block;
        margin-bottom: 0.8rem;
        color: #4a5568;
        font-weight: 500;
        font-size: 1rem;
    }

    input, select, textarea {
        width: 100%;
        padding: 1rem;
        border: 2px solid #d1d9e6;
        border-radius: 0.8rem;
        font-size: 1rem;
        transition: all 0.2s;
        background: #f8fafd;
    }

    input:focus, select:focus, textarea:focus {
        border-color: #657ef8;
        box-shadow: 0 0 0 4px rgba(101, 126, 248, 0.1);
    }

    /* 按钮样式扩展 */
    .submit-btn {
        background: linear-gradient(135deg, #657ef8, #5469d4);
        color: white;
        padding: 1rem 2rem;
        border-radius: 0.8rem;
        border: none;
        cursor: pointer;
        font-size: 1rem;
        font-weight: 500;
        transition: all 0.2s;
    }

    .export-btn {
        background: linear-gradient(135deg, #10b981, #059669);
    }

    /* 数据表格优化 */
    .salary-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0 0.8rem;
        margin-top: 1.5rem;
    }

    .salary-table th {
        background: #f8fafd;
        color: #64748b;
        padding: 1.2rem;
        font-weight: 600;
        text-align: left;
        border-bottom: 3px solid #e8ebf3;
    }

    .salary-table td {
        padding: 1.2rem;
        background: white;
        border: 2px solid #f8fafd;
        color: #4a5568;
        transition: all 0.2s;
    }

    .salary-table tr:hover td {
        transform: translateX(4px);
        box-shadow: 0 4px 6px rgba(62, 73, 89, 0.05);
    }

    /* 薪资状态标识 */
    .salary-status {
        display: inline-flex;
        padding: 0.5rem 1rem;
        border-radius: 0.6rem;
        font-size: 0.9rem;
        font-weight: 500;
        align-items: center;
        gap: 0.5rem;
    }

    .status-paid { background: #e0f2fe; color: #0ea5e9; }
    .status-pending { background: #fef3c7; color: #d97706; }
    .status-failed { background: #fee2e2; color: #dc2626; }

    /* 统计卡片 */
    .stats-container {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .stat-card {
        background: white;
        padding: 1.5rem;
        border-radius: 1rem;
        border-left: 4px solid #657ef8;
        box-shadow: 0 2px 4px rgba(62, 73, 89, 0.05);
    }

    .stat-value {
        font-size: 2rem;
        color: #1a1d2c;
        font-weight: 700;
        margin-bottom: 0.5rem;
    }

    .stat-title {
        color: #64748b;
        font-size: 0.95rem;
    }

    /* 图表容器 */
    .chart-container {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 2rem;
        margin-top: 2rem;
    }

    .chart-card {
        background: white;
        padding: 1.5rem;
        border-radius: 1rem;
        min-height: 300px;
    }

    /* 响应式设计 */
    @media (max-width: 1200px) {
        .stats-container {
            grid-template-columns: repeat(2, 1fr);
        }
        
        .chart-container {
            grid-template-columns: 1fr;
        }
    }

    @media (max-width: 768px) {
        .module-section {
            padding: 1.5rem;
        }
        
        .triple-column-form {
            grid-template-columns: 1fr;
        }
        
        .stats-container {
            grid-template-columns: 1fr;
        }
    }
    </style>
</head>
<body>
    <div class="module-section">
        <!-- 统计卡片区 -->
        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-value" id="total-expense">¥0</div>
                <div class="stat-title">本月总薪资支出</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="avg-salary">¥0</div>
                <div class="stat-title">人均月薪</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="success-rate">0%</div>
                <div class="stat-title">发放成功率</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="paid-count">0人</div>
                <div class="stat-title">已发薪人数</div>
            </div>
        </div>

        <!-- 核心功能卡 -->
        <div class="card">
            <h2 class="module-title">
                <i class="fas fa-coins"></i>
                薪资管理
            </h2>

            <!-- 查询表单 -->
            <form class="triple-column-form">
                <div class="form-group">
                    <label>发放月份</label>
                    <input type="month" id="month-filter">
                </div>
                
                <div class="form-group">
                    <label>部门筛选</label>
                    <select id="department-filter">
                        <option value="">全部部门</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>员工姓名</label>
                    <input type="text" id="name-filter" placeholder="输入员工姓名">
                </div>

                <div class="form-group" style="grid-column: 1 / -1;">
                    <button type="submit" class="submit-btn">
                        <i class="fas fa-search"></i>
                        查询薪资记录
                    </button>
                </div>
            </form>

            <!-- 操作按钮组 -->
            <div style="margin: 2rem 0; display: flex; gap: 1.5rem;">
                <button class="submit-btn export-btn">
                    <i class="fas fa-file-excel"></i>
                    导出工资表
                </button>
            </div>

            <!-- 薪资数据表格 -->
            <div id="tables-container"></div>
        </div>
    </div>

    <script>
    (function(){
        const container = document.getElementById('tables-container');
        const tbody = document.querySelector('.salary-table tbody');
        const deptSelect = document.getElementById('department-filter');
        const nameSelect = document.getElementById('name-filter');
        const monthInput = document.getElementById('month-filter');
        let allData = [];  // 存储所有薪资记录
        function loadData(){
            fetch(`/api/salaries?month=${monthInput.value}`)
            .then(res=>res.json())
            .then(json=>{
                if(json.success){
                    const data = json.data;
                    allData = data;
                    // 填充部门筛选
                    const depts = [...new Set(data.map(d=>d.department))];
                    deptSelect.innerHTML = '<option value="">全部部门</option>';
                    depts.forEach(d=>{ deptSelect.innerHTML += `<option value="${d}">${d}</option>`; });
                    // 填充员工下拉
                    nameSelect.innerHTML = '<option value="">全部员工</option>';
                    [...new Set(data.map(d=>d.name))].forEach(n=>{ nameSelect.innerHTML += `<option value="${n}">${n}</option>`; });
                    // 根据部门和员工进行过滤
                    const filtered = data.filter(item=>{
                        return (deptSelect.value === '' || item.department === deptSelect.value)
                            && (nameSelect.value === '' || item.name === nameSelect.value);
                    });
                    // 更新统计卡片
                    const total = filtered.reduce((sum, it) => sum + (it.net_salary || 0), 0);
                    const count = filtered.length;
                    const paidCount = filtered.filter(it => it.status === '已发放').length;
                    const avg = count > 0 ? total / count : 0;
                    const rate = count > 0 ? Math.round(paidCount / count * 100) : 0;
                    document.getElementById('total-expense').textContent = `¥${total.toFixed(2)}`;
                    document.getElementById('avg-salary').textContent = `¥${avg.toFixed(2)}`;
                    document.getElementById('success-rate').textContent = `${rate}%`;
                    document.getElementById('paid-count').textContent = `${paidCount}人`;
                    // 渲染表格（所有员工）
                    container.innerHTML = '';
                    // 月份标题
                    const m = monthInput.value;
                    const title = document.createElement('h3');
                    title.textContent = m;
                    container.appendChild(title);
                    // 构建表格
                    const table = document.createElement('table');
                    table.className = 'salary-table';
                    table.innerHTML = `
                        <thead>
                            <tr>
                                <th>员工姓名</th>
                                <th>部门</th>
                                <th>基本工资</th>
                                <th>奖金</th>
                                <th>扣款项</th>
                                <th>实发工资</th>
                                <th>发放状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody></tbody>`;
                    const tbodyMonth = table.querySelector('tbody');
                    // 渲染所有员工行
                    filtered.forEach(item=>{
                        const statusClass = item.status==='已发放'?'status-paid':'status-pending';
                        const icon = item.status==='已发放'?'fa-check-circle':'fa-clock';
                        const tr = document.createElement('tr');
                        tr.dataset.empcode = item.employee_code;
                        tr.innerHTML = `
                            <td>${item.name}</td>
                            <td>${item.department}</td>
                            <td>${item.base_salary!=null? '¥'+item.base_salary : ''}</td>
                            <td>${item.bonus!=null? '¥'+item.bonus : ''}</td>
                            <td>${item.deductions!=null? '¥'+item.deductions : ''}</td>
                            <td>${item.net_salary!=null? '¥'+item.net_salary : ''}</td>
                            <td><span class="salary-status ${statusClass}"><i class="fas ${icon}"></i>${item.status}</span></td>
                            <td>
                                <button class="action-btn" data-action="edit" data-id="${item.id||''}" style="color:#657ef8"><i class="fas fa-edit fa-lg"></i></button>
                                <button class="action-btn" data-action="delete" data-id="${item.id||''}" style="color:#ef4444"><i class="fas fa-trash fa-lg"></i></button>
                                <button class="action-btn" data-action="toggle" data-id="${item.id||''}" style="color:#10b981"><i class="fas fa-exchange-alt fa-lg"></i></button>
                            </td>`;
                        tbodyMonth.appendChild(tr);
                    });
                    container.appendChild(table);
                }
            });
        }
        // 设置默认月份为当前月
        const now = new Date();
        monthInput.value = now.toISOString().slice(0,7);
        // 初始加载
        loadData();
        // 表单提交查询
        document.querySelector('.triple-column-form').addEventListener('submit', e=>{
            e.preventDefault();
            loadData();
        });
        // 部门改变时更新员工下拉，并清空当前选中员工
        deptSelect.addEventListener('change', ()=>{
            const dep = deptSelect.value;
            const names = allData.filter(it=>!dep||it.department===dep).map(it=>it.name);
            nameSelect.innerHTML = '<option value="">全部员工</option>';
            [...new Set(names)].forEach(n=> nameSelect.innerHTML += `<option value="${n}">${n}</option>`);
        });
        // 添加筛选及操作事件处理
        container.addEventListener('click', function(event) {
            const btn = event.target.closest('.action-btn');
            if (!btn) return;
            const action = btn.dataset.action;
            const id = btn.dataset.id;
            const tr = btn.closest('tr');
            if (action === 'edit') {
                if (btn.dataset.editing) {
                    // 保存更新
                    const inputs = tr.querySelectorAll('input');
                    const [baseInput, bonusInput, dedInput, netInput] = inputs;
                    const base_salary = parseFloat(baseInput.value) || 0;
                    const bonus = parseFloat(bonusInput.value) || 0;
                    const deductions = parseFloat(dedInput.value) || 0;
                    const net_salary = parseFloat(netInput.value) || 0;
                    if (!id) {
                        // 创建新薪资记录
                        const emp = tr.dataset.empcode;
                        fetch('/api/salaries', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({ employee_code: emp, base_salary, bonus, deductions, net_salary, month: monthInput.value })
                        })
                        .then(res => res.json())
                        .then(json => {
                            if (json.success) {
                                btn.removeAttribute('data-editing');
                                btn.innerHTML = '<i class="fas fa-edit fa-lg"></i>';
                                loadData();
                            } else {
                                alert(json.message);
                            }
                        });
                    } else {
                        // 更新已有记录
                        fetch(`/api/salaries/${id}`, {
                            method: 'PUT',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({ base_salary, bonus, deductions, net_salary })
                        })
                        .then(res => res.json())
                        .then(json => {
                            if (json.success) {
                                btn.removeAttribute('data-editing');
                                btn.innerHTML = '<i class="fas fa-edit fa-lg"></i>';
                                loadData();
                            } else {
                                alert(json.message);
                            }
                        });
                    }
                } else {
                    // 切换到编辑模式
                    const tds = tr.querySelectorAll('td');
                    const parseVal = idx => parseFloat(tds[idx].textContent.replace(/[^0-9.]/g, '')) || 0;
                    const vBase = parseVal(2);
                    const vBonus = parseVal(3);
                    const vDed = parseVal(4);
                    tds[2].innerHTML = `<input type="number" class="base-input" value="${vBase}" style="width:100%">`;
                    tds[3].innerHTML = `<input type="number" class="bonus-input" value="${vBonus}" style="width:100%">`;
                    tds[4].innerHTML = `<input type="number" class="ded-input" value="${vDed}" style="width:100%">`;
                    // 自动计算实发工资，只读输入框
                    const initNet = (vBase + vBonus - vDed).toFixed(2);
                    tds[5].innerHTML = `<input type="number" class="net-input" value="${initNet}" readonly style="width:100%">`;
                    // 实时计算
                    const baseInp = tr.querySelector('.base-input');
                    const bonusInp = tr.querySelector('.bonus-input');
                    const dedInp = tr.querySelector('.ded-input');
                    const netInp = tr.querySelector('.net-input');
                    [baseInp, bonusInp, dedInp].forEach(inp => inp.addEventListener('input', () => {
                        const b = parseFloat(baseInp.value) || 0;
                        const bo = parseFloat(bonusInp.value) || 0;
                        const d = parseFloat(dedInp.value) || 0;
                        netInp.value = (b + bo - d).toFixed(2);
                    }));
                    btn.dataset.editing = 'true';
                    btn.innerHTML = '<i class="fas fa-save fa-lg"></i>';
                }
            } else if (action === 'delete') {
                // 清空该员工薪资信息
                if (!id) return;
                if (!confirm('确定清空该员工的所有薪资信息吗？')) return;
                fetch(`/api/salaries/${id}`, {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ base_salary: null, bonus: null, deductions: null, net_salary: null })
                })
                .then(res => res.json())
                .then(json => {
                    if (json.success) {
                        loadData();
                    } else {
                        alert(json.message);
                    }
                });
            } else if (action === 'toggle') {
                // 切换发放状态
                if (!id) return;
                const statusSpan = tr.querySelector('.salary-status');
                const curText = statusSpan.textContent.trim();
                const newStatus = curText === '未发放' ? '已发放' : '未发放';
                fetch(`/api/salaries/${id}`, {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ status: newStatus })
                })
                .then(res => res.json())
                .then(json => {
                    if (json.success) {
                        loadData();
                    } else {
                        alert(json.message);
                    }
                });
            }
        });
        // 导出按钮点击
        document.querySelector('.export-btn').addEventListener('click', function(){
            const m = monthInput.value;
            // 打开下载链接
            window.open(`/api/salaries/export?month=${m}`, '_blank');
        });
    })();
    </script>
</body>
</html>